/*******************************************************************************
 * Copyright (c) 2006 CEA List.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     CEA List - initial API and implementation
 *******************************************************************************/
package com.cea.papyrus.diagram.deployment.command;

import org.eclipse.draw2d.geometry.Point;
import org.eclipse.uml2.uml.CommunicationPath;
import org.eclipse.uml2.uml.Element;
import org.eclipse.uml2.uml.NamedElement;
import org.eclipse.uml2.uml.Property;

import com.cea.papyrus.diagraminterchange2.di2.GraphEdge;
import com.cea.papyrus.diagraminterchange2.di2.GraphElement;

/**
 * 
 */
public class CommunicationPathReconnectCommand extends AssociationReconnectCommand{

	/**
	 * 
	 * 
	 * @param newEndpoint 
	 * @param end 
	 * @param conn 
	 * @param newLocation 
	 */
	public CommunicationPathReconnectCommand(GraphEdge conn, GraphElement newEndpoint, Point newLocation, int end) {
		super(conn, newEndpoint, newLocation, end);
	}

	/**
	 * Moves the association to its new source/target elements.
	 * 
	 * @param umlTarget the new  target Classifier for the association
	 * @param umlSource the new source Classifier for the association
	 */
	public void moveAssociation(Element umlSource, Element umlTarget){
		CommunicationPath obj=(CommunicationPath)getEdgeElement();
		((NamedElement)obj).setName("C_" +((NamedElement)umlSource).getName()+ "_"+ ((NamedElement)umlTarget).getName());
		CommunicationPath asso=(CommunicationPath)obj;
		// Relation has moved!!
		Property p1= (Property)asso.getMemberEnds().get(0);
		Property p2= (Property)asso.getMemberEnds().get(1);
		org.eclipse.uml2.uml.Classifier movableClassifier;
		Property fixProperty=null;
		Property movableProperty=null;
	
		if ((p1.getType()==umlTarget)||(p1.getType()==umlSource)){
			movableProperty=p1;
			fixProperty=p2;
	
	
		}
		if ((p2.getType()==umlTarget)||(p2.getType()==umlSource)){
			movableProperty=p2;
			fixProperty=p1;
		}
		if (movableProperty.getType()==umlTarget){
			movableClassifier=(org.eclipse.uml2.uml.Classifier)umlSource;}
		else{movableClassifier=(org.eclipse.uml2.uml.Classifier)umlTarget;}
	
		//move
		if(movableProperty.getOwner()!=asso){//changeParent if not belong to association
			if ( movableProperty.getOwner() instanceof org.eclipse.uml2.uml.Class){
				((org.eclipse.uml2.uml.Class)movableProperty.getOwner()).getOwnedAttributes().remove(p1);
			}
			if ( movableClassifier instanceof org.eclipse.uml2.uml.Class){
				((org.eclipse.uml2.uml.Class)movableClassifier).getOwnedAttributes().add(movableProperty);	
			}
		}
		fixProperty.setType(movableClassifier);
	}

}